package com.parseword1;

public class WordList{

	int capacity = 30;
	char[] cache = new char[capacity];
	int writeIndex = 0;
	
	
	// 扩大容量
	public void expandcapacity(int capacity){
		if(capacity <= writeIndex){
			return;
		}
		char[] ncache = new char[capacity]; // 新的存储
		System.arraycopy(this.cache, 0, ncache, 0, writeIndex);
		this.capacity = capacity;
		this.cache = ncache;
	}
	public void add(short c){
		add((char)c);
	}
	public void add(char c){
		verifycapacity(1);
		cache[writeIndex++] = c;
	}
	public void add(char[] cs){
		int csLength = cs.length;
		verifycapacity(csLength);
		System.arraycopy(cs, 0, cache, writeIndex, csLength);
		writeIndex+=csLength;
	}
	private void verifycapacity(int len){
		if(this.capacity - this.writeIndex < len){
			expandcapacity((len/this.capacity+2)*this.capacity);
		}
	}
	
	public char get(int i){
		if(i>=writeIndex){
			throw new IndexOutOfBoundsException(String.valueOf(i));
		}
		return this.cache[i];
	}
	
	public char[] toArrays(){
		char[] cs = new char[writeIndex];
		System.arraycopy(cache, 0, cs, 0, writeIndex);
		return cs;
	}
	@Override
	public String toString() {
		
		return new String(toArrays());
	}
	
}
